import { _decorator, CCFloat, Collider, Component, ICollisionEvent, math, Node, v3, Vec3 } from 'cc';
import { ProjectileProperty } from "./ProjectileProperty";
import { Events } from "../events/Events";
import { MathUtil } from '../utils/MathUtil';
import { EffectManager } from '../level/EffectManager';
import { ResourceDefine } from '../resource/ResourceDefine';
import { AudioManager } from '../level/AudioManager';
const { ccclass, property, requireComponent } = _decorator;


let tempPosition: Vec3 = v3();
let tempDirection: Vec3 = v3();
let forward: Vec3 = v3();

//箭矢 类
@ccclass('Projectile')
export class Projectile extends Component {

    // 移动速度
    @property(CCFloat)
    linearSpeed:number = 3;

    // 角速度
    @property(CCFloat)
    angularSpeed:number = 180;

    // 主人
    host:Node = null;

    // 当前子弹属性
    projectileProperty:ProjectileProperty = new ProjectileProperty()

    // 监听碰撞体
    collider:Collider = null;

    // 是否具有追踪能力，追踪目标
    target: Node = null;

    // 生成时间
    startTime: number = 0;

    private position: Vec3 = v3()


    start() {
        this.collider = this.node.getComponent(Collider);
        // 监听碰撞时间事件
        this.collider?.on("onTriggerEnter", this.onTriggerEnter, this);

    }

    onDestroy(){

    }


    fire()
    {
        this.startTime = 0;
    }

    update(deltaTime: number) {

        this.startTime  += deltaTime;
        if(this.startTime >= this.projectileProperty.lifeTime)
        {
            this.node.emit(Events.OnProjectileDead, this);
            return;
        }

        // 移动 跟踪
        if(this.target != null)
        {
            // 计算目标角度

            // 目标方向
            Vec3.subtract(tempDirection, this.node.worldPosition, this.target.worldPosition)
            tempDirection.normalize();

            // 角速度转化为角弧度
            const angle = math.toRadian(this.angularSpeed) * deltaTime;
            // 计算最新角度
            MathUtil.rotateToward(forward, this.node.forward, tempDirection, angle);
            this.node.forward = forward;
        }

        // 位置 = 当前位置 + 速度 * 时间
        Vec3.scaleAndAdd(this.position, this.node.worldPosition, this.node.forward, this.linearSpeed * deltaTime);
        this.position.y = this.node.worldPosition.y;
        this.node.worldPosition = this.position;
     
    }

    onTriggerEnter(event:ICollisionEvent){
        // 穿透子弹逻辑
        this.projectileProperty.penetration--;
        if(this.projectileProperty.penetration <= 0)
        {
            // 碰撞后子弹销毁
            this.node.emit(Events.OnProjectileDead, this);
        }   
        
        // 播放击中特效
        EffectManager.instance.play(ResourceDefine.EffExplore, event.otherCollider.node.worldPosition);
        // 播放击中音频
        AudioManager.instance.playHitSfx();
    }
   

    reset() {
        // 重置所有需要初始化的属性
        // 比如位置、速度、生命值等
    }
}

